package src.clientSide;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Stack;

import src.messagesToClient.MessageToClient;
import src.messagesToServer.MessageToServer;



public class CCom {
	private static int port = 12345;
	private static Socket server = new Socket();
	private static SocketAddress address = new InetSocketAddress("localhost",port);
	private static ObjectOutputStream out;
	private static ObjectInputStream in;
	
	private static Stack<MessageToServer> previousMessages = new Stack<MessageToServer>();
	private static Stack<MessageToServer> nextMessages = new Stack<MessageToServer>();
	
	public static void handle(MessageToServer message) {
		if (message.redoable) push(message);
		try {
			if (!server.isConnected()) {
				server.connect(address);
				out = new ObjectOutputStream(server.getOutputStream());
				in = new ObjectInputStream(server.getInputStream());
			}
			out.writeObject(message);
			Object response = in.readObject();
			if (response instanceof MessageToClient) {
				((MessageToClient) response).execute();
			}
		} catch (IOException e) {
			System.out.println("Error: Client Communicator IOException");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Error: Client Communicator Class Not Found Exception");
			e.printStackTrace();
		}
	}
	
	/**
	 * Places a message in the message lists.  As if a new page is visited in a browser
	 * @param message The next message to add
	 */
	private static void push(MessageToServer message) {
		previousMessages.push(message);
		nextMessages.clear();
	}
	
	/**
	 * Moves the list back, and sends the previous message to the server
	 * @return Returns true if a message was sent to the server
	 */
	public static boolean back() {
		if (!previousMessages.isEmpty()) {
			nextMessages.push(previousMessages.pop());
			if (!previousMessages.isEmpty()) {
				handle(previousMessages.peek());
				return true;
			}
		}
		return false;
	}

	/**
	 * Sends the last message to the server
	 * @return Returns true if a message was sent to the server
	 */
	public static boolean reload() {
		if (!previousMessages.isEmpty()) {
			handle(previousMessages.peek());
			return true;
		}
		return false;
	}
	
	/**
	 * Moves the list forward, and sends the next message to the server
	 * @return Returns true if a message was sent to the server
	 */
	public static boolean forward() {
		if (!nextMessages.isEmpty()) {
			previousMessages.push(nextMessages.pop());
			handle(previousMessages.peek());
			return true;
		}
		return false;
	}
	
}
